/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.util.ByteArrayBuffer;

/**
 *
 * @author Bor
 */
@WebServlet(urlPatterns = {"/geocoder"})
public class geocoder extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */

            String params = "";
            String adr = "";
            String fadr = "";
            String reqAdr = "";
            String extFileData = "";
            String outString = "";
            String outStringErr = "";
            String line;
            Integer lineCount = 0;

            Enumeration enParam = request.getParameterNames();
            while (enParam.hasMoreElements()) {
                String paramName = (String) enParam.nextElement();
                params += "[" + paramName + "=" + request.getParameter(paramName) + "]";
                if (paramName.equals("adr")) {
                    adr = request.getParameter(paramName);
                }
            }
            String webData = "";
            String sender = "";
            try {
                // debug
                // webDataAr[0] = "120|5000";

                Date cDate = new Date();
                        // int tmpInt = Integer.parseInt(webDataAr[0])+1;
                // if (tmpInt>360){tmpInt=3;}
                // webDataAr[0] = tmpInt+"";

                // locX=777;
                // locY=777;
                // String sender
                // ="v="+cDate.toString()+"&lX="+aValues[0]+"&lY="+aValues[1]+
                // "&v0="+mValues[0]+"&v1="+mValues[1]+"&v2="+mValues[2];
                Calendar cal = new GregorianCalendar();
                int month = cal.get(Calendar.MONTH);
                month++;
                //String todayIs= cal.get(Calendar.YEAR) + "-" + month + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + " ";
                String todayIs = cal.get(Calendar.YEAR) + "o" + month + "o" + cal.get(Calendar.DAY_OF_MONTH) + "o" + cal.get(Calendar.HOUR_OF_DAY) + "o" + cal.get(Calendar.MINUTE) + "o" + cal.get(Calendar.SECOND) + "o";

                sender = "http://maps.googleapis.com/maps/api/geocode/json?address=Ставрополь";

                //URLEncoder.encode(adr +" " + city + " " + region, "UTF8");
                //String urlStr = "http://92.63.96.27:8180/wm/wm_s?" + sender;
                //---LOAD FROM FILE------------------------------------------------------------
                // process the line.
                BufferedReader br = new BufferedReader(new FileReader("C:\\system\\temp\\111.txt"));
                while ((line = br.readLine()) != null) {
                    lineCount++;
                    try {

                        //reqAdr = "Ставропольский+край+Вязники+Железнодорожная+9";
                        String urlStr = "http://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(line, "UTF8");

                        URL myURL = new URL(urlStr);
                        URLConnection ucon = myURL.openConnection();

                        InputStream is = ucon.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);
                        ByteArrayBuffer baf = new ByteArrayBuffer(50);
                        try {
                            int current = 0;
                            while ((current = bis.read()) != -1) {
                                baf.append((byte) current);
                            }
                            webData = new String(baf.toByteArray());
                        } finally {
                            // baf.clear();
                            bis.close();
                        }
                        if (!webData.equalsIgnoreCase("-")) {
                            String tStr=webData.substring(webData.indexOf("formatted_address")+21);
                            String formatname = tStr.substring(1,tStr.indexOf("geometry"));
                            String longlat = tStr.substring(tStr.indexOf("location\""),tStr.indexOf("location_"));
                            outString+=line+"|"+ formatname+"|"+longlat+"|"+"<hr/>";//.substring(webData.indexOf("location"),webData.indexOf("location_type"))+"<hr/>";                            
//                            StringTokenizer st = new StringTokenizer(webData, "{");
//                            while (st.hasMoreTokens()) {
//                                outString += st.nextToken().trim();
//                            }

                            //outString = "'" + extFileData + "'+'|'+'" + line + "'+'|'+response.results[0].formatted_address+'|'+response.results[0].geometry.location.lat+'|'+response.results[0].geometry.location.lng;+'|';\n";
                            //fadr = adr.substring(adr.indexOf("formated_address"), adr.length());
//                    for (int i = 0; i < 99; i++) {
//                        webDataAr[i + 1] = webDataAr[i];
//                        webDataArTm[i + 1] = webDataArTm[i];
//                    }
                            // <<<<<<< .mine
                            // StringTokenizer st = new StringTokenizer(webData,"|");
                            // int i=0;
                            // / while (st.hasMoreTokens()) {
                            // webDataAr[i] = st.nextToken().trim();
                            // i++;
                            // }
                            // =======
//                    webDataAr[0] = webData.trim();
//                                // webDataAr[0] = "120|5000";
//                    // >>>>>>> .r93
//                    Log.d("ar_wSndr:", "webData1 [" + webData + "]");
//                    // webDataAr[0] = "180";
//                    webDataArTm[0] = System.currentTimeMillis();
                        }

                    } catch (Exception err) {
                    }
                }
                br.close();

                // inetView.setText("inet answ: " + new
                // String(baf.toByteArray()));
                // inetView.setText("inet answ: " + sender);
                // Toast.makeText(this,
                // "Sended to web!:"+sender,Toast.LENGTH_LONG).show();
//                Log.d("ar_wSndr:", "ar_" + urlStr + " >>> " + baf.toByteArray());
            } catch (Exception e) {
                // ex = e;
                // Log.e(getClass().getSimpleName(), "problem encountered", e);
                e.printStackTrace();
//                Log.d("wSndrErr", e.toString());
                outStringErr = e.toString();

            }

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet geocoder</title>"
                    + ""
                    + "<script src=\"js/jquery-1.11.2.min.js\"></script>");
            out.println("<script >function init(){\n"
                    + "var response=" + webData + ";\n"//extFileData
                    + "var outString ='" + outString + "\n';"
                    + "$('#console').text(outString);\n"
                    + "\n"
                    + "}\n"
                    + "</script></head>");
            out.println("<body onLoad='init()'>" + params + "<hr/>" + sender + "<hr/>" + webData + "<hr/>fadr:" + fadr);
            out.println("<h1>Servlet geocoder at " + request.getContextPath() + "</h1>");
            out.println("<div id='console'> </div>");
            out.println("<div style='border:solid gray 1px'>" + outString + " </div><hr/>");
            out.println("<div style='border:solid red 1px'>" + outStringErr + " </div><hr/>");
            out.println("<div style='border:solid blue 1px'>" + lineCount + " </div><hr/>");
            out.println("<div style='border:solid green 1px'>" + webData + " </div>");

            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
